#include "attendancetimemanager.h"

#include <QFile>

QMap<QString, DailySettings> AttendanceTimeManager::m_settings;

// 星期名称映射表
const QMap<int, QString> AttendanceTimeManager::m_weekdayMap = {
    {1, "Monday"},
    {2, "Tuesday"},
    {3, "Wednesday"},
    {4, "Thursday"},
    {5, "Friday"},
    {6, "Saturday"},
    {7, "Sunday"}
};

// 构造函数
AttendanceTimeManager::AttendanceTimeManager(const QString configPath,
                                             QObject *parent)
    : QObject{parent}
    , m_iniManager{configPath, Q_NULLPTR}
{
    // m_iniManager = new iniManager{configPath, this};

    if (!loadSettings()) {
        initDefaultSettings();
        saveSettings();
    }
}


// 初始化默认配置
void AttendanceTimeManager::initDefaultSettings()
{
    const QTime defaultStart(9, 0);
    const QTime defaultEnd(18, 0);

    const QMap<QString, DailySettings> defaultSettings = {
        {"Monday",    {defaultStart, defaultEnd, true}},
        {"Tuesday",   {defaultStart, defaultEnd, true}},
        {"Wednesday", {defaultStart, defaultEnd, true}},
        {"Thursday",  {defaultStart, defaultEnd, true}},
        {"Friday",    {defaultStart, defaultEnd, true}},
        {"Saturday",  {defaultStart, defaultEnd, false}},
        {"Sunday",    {defaultStart, defaultEnd, false}}
    };

    m_settings = defaultSettings;
}

// 保存配置
bool AttendanceTimeManager::saveSettings()
{

    bool success = true;
    for (auto it = m_settings.constBegin(); it != m_settings.constEnd(); ++it) {
        const QString &group = it.key();
        const DailySettings &settings = it.value();

        if (!m_iniManager.writeValues(group, settings.toVariantMap())) {
            success = false;
        }
    }
    return success && m_iniManager.sync();
}

// 加载配置
bool AttendanceTimeManager::loadSettings()
{
    const QStringList days = {"Monday", "Tuesday", "Wednesday",
                              "Thursday", "Friday", "Saturday", "Sunday"};

    bool hasValidData = false;
    foreach (const QString &day, days) {
        QVariantMap data = {
            {"StartTime", m_iniManager.readValue(day, "StartTime")},
            {"EndTime", m_iniManager.readValue(day, "EndTime")},
            {"Enabled", m_iniManager.readValue(day, "Enabled")}
        };

        if (!data.isEmpty()) {
            m_settings[day] = DailySettings::fromVariantMap(data);
            hasValidData = true;
        }
    }
    return hasValidData;
}

// 设置每日配置
void AttendanceTimeManager::setDailySettings(const QString &weekday, const DailySettings &settings)
{
    if (m_settings.contains(weekday)) {
        m_settings[weekday] = settings;
    }
}

// 获取每日配置
DailySettings AttendanceTimeManager::getDailySettings(const QString &weekday) const
{
    return m_settings.value(weekday, DailySettings{QTime(), QTime(), false});
}

QMap<QString, DailySettings> AttendanceTimeManager::getAllSettings() const { return m_settings; }

